// pages/personalCenter/index.js
const { userApi, appointmentApi } = require("../../utils/api.js");
const { cleanAvatarUrl } = require("../../utils/avatar.js");

Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 用户信息
    userInfo: null, // 初始为null，表示未登录
    // 用户设置
    userSettings: {
      phone_hidden: false,
      perfect_hidden: false,
      setting1: "", // 动态标题
      setting2: "",
      setting3: "",
    },
    // 统计数据
    statistics: {
      totalAppointments: 0,
      todayCompleted: 0,
      totalCompleted: 0,
    },
    // 功能菜单
    menuList: [
      {
        id: 1,
        icon: "🛍️",
        title: "商品维护",
        desc: "管理商品信息",
        url: "",
        action: "productMaintain",
        adminOnly: true,
      },
      {
        id: 2,
        icon: "📅",
        title: "我的预约",
        desc: "查看预约记录",
        url: "",
        action: "myAppointments",
      },
      {
        id: 3,
        icon: "👤",
        title: "完善信息",
        desc: "完善个人资料",
        url: "/pages/completeProfile/index",
        action: "completeProfile",
        requireLogin: true,
        dynamicTitle: true, // 标记为动态标题
      },
      {
        id: 4,
        icon: "🖼️",
        title: "轮播图管理",
        desc: "管理首页轮播图",
        url: "",
        action: "bannerManage",
        adminOnly: true,
      },
      {
        id: 5,
        icon: "👥",
        title: "管理",
        desc: "管理",
        url: "",
        action: "userManage",
        adminOnly: true,
      },
    ],
    // 设置菜单
    settingList: [
      {
        id: 1,
        icon: "📅",
        title: "工作时间日历",
        desc: "设置未来七天工作时间",
        url: "/pages/workTimeCalendar/index",
        adminOnly: true,
      },
      {
        id: 1.5,
        icon: "👥",
        title: "美甲师人数设置",
        desc: "设置美甲师人数",
        url: "/pages/staffCountSetting/index",
        adminOnly: true,
      },
      {
        id: 2,
        icon: "🔔",
        title: "消息通知",
        desc: "开启微信消息通知",
        url: "",
        action: "notification",
      },
      {
        id: 3,
        icon: "📞",
        title: "联系客服",
        desc: "拨打电话",
        dynamicDesc: true, // 标记为动态描述
        url: "",
        action: "contact",
      },
      {
        id: 4,
        icon: "🚪",
        title: "立即登录",
        desc: "登录账号",
        url: "",
        action: "login",
        showWhenLoggedOut: true,
      },
      {
        id: 5,
        icon: "📋",
        title: "隐私政策",
        desc: "查看隐私政策",
        url: "/pages/privacy/index",
        action: "privacy",
      },
      {
        id: 6,
        icon: "🚪",
        title: "退出登录",
        desc: "退出当前账号",
        url: "",
        action: "logout",
        showWhenLoggedIn: true,
      },
      {
        id: 7,
        icon: "🗑️",
        title: "注销账号",
        desc: "永久删除账号及数据",
        url: "",
        action: "deleteAccount",
        showWhenLoggedIn: true,
      },
    ],
    // 加载状态
    loading: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.checkAdminStatus();
    this.loadUserData();
    this.loadUserSettings();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 每次显示页面时刷新数据
    this.checkAdminStatus();
    this.loadUserData();
    this.loadUserSettings();

    // 更新tabBar
    const app = getApp();
    if (app && app.updateTabBar) {
      app.updateTabBar();
    }
  },

  /**
   * 检查管理员状态
   */
  async checkAdminStatus() {
    const userInfo = wx.getStorageSync("userInfo");
    const token = wx.getStorageSync("token");

    if (!userInfo || !token) {
      this.setData({
        isAdmin: false,
        userInfo: null,
      });
      return;
    }

    try {
      // 通过API获取用户角色信息
      const { userApi } = require("../../utils/api.js");
      const result = await userApi.getUserInfo();

      if (result && result.code === 0) {
        const userData = result.data;
        this.setData({
          isAdmin: userData.isAdmin || false,
          userInfo: userData,
        });
      } else {
        // API失败时使用本地存储的数据
        const isAdmin =
          userInfo && (userInfo.isAdmin || userInfo.role === "admin");
        this.setData({
          isAdmin: isAdmin,
          userInfo: userInfo,
        });
      }
    } catch (error) {
      // 出错时使用本地存储的数据
      const isAdmin =
        userInfo && (userInfo.isAdmin || userInfo.role === "admin");
      this.setData({
        isAdmin: isAdmin,
        userInfo: userInfo,
      });
    }
  },

  /**
   * 加载用户数据
   */
  async loadUserData() {
    try {
      // 从本地存储获取用户信息
      const localUserInfo = wx.getStorageSync("userInfo");

      if (!localUserInfo) {
        this.setData({
          userInfo: null,
        });
        return;
      }

      // 从API获取最新的用户信息（包括头像）
      try {
        const result = await userApi.getUserInfo();

        if (result.code === 0 && result.data) {
          // 直接使用服务器返回的用户数据
          let userData = result.data;

          // 确保头像URL是完整的HTTPS URL
          if (userData.avatar) {
            userData.avatar = cleanAvatarUrl(userData.avatar);
          }

          // 更新本地存储的用户信息
          wx.setStorageSync("userInfo", userData);
          this.setData({
            userInfo: userData,
          });
        } else {
          // API失败时使用本地存储的信息
          this.setData({
            userInfo: localUserInfo,
          });
        }
      } catch (apiError) {
        // 使用统一的错误处理
        const { handleApiError } = require("../../utils/auth.js");
        handleApiError(apiError, (error) => {
          // 自定义错误处理：使用本地存储的信息
          this.setData({
            userInfo: localUserInfo,
          });
        });
        return; // 如果token过期，直接返回，不继续执行
      }

      // 加载统计数据
      this.loadStatistics();
    } catch (error) {
      // 出错时设置为null，表示未登录
      this.setData({
        userInfo: null,
      });
    }
  },

  /**
   * 加载用户设置
   */
  async loadUserSettings() {
    try {
      const { settingsApi } = require("../../utils/api.js");
      const result = await settingsApi.getUserSettings();

      console.log("用户设置API响应:", result);

      if (result && result.code === 0) {
        console.log("用户设置数据:", result.data);
        this.setData({
          userSettings: result.data,
        });
        // 更新动态标题
        this.updateDynamicTitles();
      } else {
        console.log("用户设置API失败，使用默认设置");
        // 如果获取失败，使用默认设置
        this.setData({
          userSettings: {
            phone_hidden: false,
            perfect_hidden: false,
            setting1: "",
            setting2: "",
            setting3: "",
          },
        });
      }
    } catch (error) {
      console.log("用户设置API异常:", error);
      // 出错时使用默认设置
      this.setData({
        userSettings: {
          phone_hidden: false,
          perfect_hidden: false,
          setting1: "",
          setting2: "",
          setting3: "",
        },
      });
    }
  },

  /**
   * 更新动态标题
   */
  updateDynamicTitles() {
    const { userSettings, menuList } = this.data;

    // 更新菜单中的动态标题和描述
    const updatedMenuList = menuList.map((item) => {
      if (item.dynamicTitle && item.id === 3) {
        // 直接使用setting1的值作为标题
        return {
          ...item,
          title: userSettings.setting1 || "",
        };
      }
      if (item.dynamicDesc && item.id === 2) {
        // 直接使用setting2的值作为描述
        return {
          ...item,
          desc: userSettings.setting2 || "",
        };
      }
      return item;
    });

    this.setData({
      menuList: updatedMenuList,
    });
  },

  /**
   * 加载统计数据
   */
  async loadStatistics() {
    try {
      // 检查用户是否已登录
      const localUserInfo = wx.getStorageSync("userInfo");
      if (!localUserInfo) {
        // 用户未登录，使用默认数据
        this.setData({
          statistics: {
            totalAppointments: 0,
            todayCompleted: 0,
            totalCompleted: 0,
          },
        });
        return;
      }

      // 从数据库获取预约数据
      try {
        // 获取所有预约数据，设置较大的页面大小
        const result = await appointmentApi.getAppointments({
          page: 1,
          page_size: 100000, // 设置较大的页面大小以获取所有数据
        });

        if (result.code === 0 && result.data) {
          // 处理 appointments 数据，确保是数组
          let appointments = [];
          if (result.data.list && Array.isArray(result.data.list)) {
            appointments = result.data.list;
          } else if (Array.isArray(result.data)) {
            appointments = result.data;
          }

          // 如果 appointments 仍然不是数组，设置为空数组
          if (!Array.isArray(appointments)) {
            appointments = [];
          }

          // 计算统计数据
          const totalAppointments = appointments.length;

          // 今日完成的预约（状态为已完成且预约日期是今天的）
          const today = new Date().toISOString().split("T")[0];

          const todayCompleted = appointments.filter((apt) => {
            const isCompleted = apt.status === 3;
            const isToday = apt.appointment_date === today;
            return isCompleted && isToday;
          }).length;

          // 共计完成的预约（状态为已完成的预约）
          const totalCompleted = appointments.filter((apt) => {
            return apt.status === 3; // 状态为已完成
          }).length;

          this.setData({
            statistics: {
              totalAppointments: totalAppointments,
              todayCompleted: todayCompleted,
              totalCompleted: totalCompleted,
            },
          });
        } else {
          // 出错时使用默认数据
          this.setData({
            statistics: {
              totalAppointments: 0,
              todayCompleted: 0,
              totalCompleted: 0,
            },
          });
        }
      } catch (apiError) {
        // 使用统一的错误处理
        const { handleApiError } = require("../../utils/auth.js");
        handleApiError(apiError, (error) => {
          // 自定义错误处理：使用默认数据
          this.setData({
            statistics: {
              totalAppointments: 0,
              todayCompleted: 0,
              totalCompleted: 0,
            },
          });
        });
        return; // 如果token过期，直接返回
      }
    } catch (error) {
      // 出错时使用默认数据
      this.setData({
        statistics: {
          totalAppointments: 0,
          todayCompleted: 0,
          totalCompleted: 0,
        },
      });
    }
  },

  /**
   * 菜单点击事件
   */
  onMenuTap(e) {
    const { item } = e.currentTarget.dataset;

    // 检查管理员权限
    if (item.adminOnly && !this.data.isAdmin) {
      wx.showToast({
        title: "权限不足",
        icon: "none",
      });
      return;
    }

    // 检查登录状态（需要登录的功能）
    if (item.requireLogin && !this.data.userInfo) {
      // 对于完善信息，使用对话框提示
      if (item.action === "completeProfile") {
        const { userSettings } = this.data;
        const title = userSettings.setting1 || "";

        wx.showModal({
          title: "需要登录",
          content: `请先登录后再${title}`,
          confirmText: "去登录",
          cancelText: "取消",
          success: (res) => {
            if (res.confirm) {
              wx.navigateTo({
                url: "/pages/login/index",
              });
            }
          },
        });
      } else {
        wx.showToast({
          title: "请先登录",
          icon: "none",
        });
      }
      return;
    }

    // 检查登录状态显示条件
    const userInfo = wx.getStorageSync("userInfo");
    const isLoggedIn = !!userInfo;

    if (item.showWhenLoggedIn && !isLoggedIn) {
      return; // 未登录时不显示"退出登录"
    }

    if (item.showWhenLoggedOut && isLoggedIn) {
      return; // 已登录时不显示"立即登录"
    }

    if (item.action) {
      this.handleSpecialAction(item.action);
    } else if (item.url) {
      wx.navigateTo({
        url: item.url,
      });
    }
  },

  /**
   * 处理特殊操作
   */
  handleSpecialAction(action) {
    switch (action) {
      case "contact":
        this.contactService();
        break;
      case "bannerManage":
        this.manageBannerImages();
        break;
      case "productMaintain":
        this.productMaintain();
        break;
      case "myAppointments":
        this.myAppointments();
        break;
      case "completeProfile":
        this.goToCompleteProfile();
        break;
      case "login":
        this.goToLogin();
        break;
      case "logout":
        this.logout();
        break;
      case "deleteAccount":
        this.deleteAccount();
        break;
      case "privacy":
        this.goToPrivacy();
        break;
      case "userManage":
        this.userManage();
        break;
      case "notification":
        this.requestNotificationAuthorization();
        break;
    }
  },

  /**
   * 请求消息通知授权（分步请求，每次用户点击只请求一个模板）
   * 注意：必须由用户点击触发，不能自动调用
   */
  requestNotificationAuthorization() {
    // 检查已授权的模板
    const hasCancelMessage = wx.getStorageSync("hasSubscribedCancelMessage");
    const hasNewAppointmentMessage = wx.getStorageSync("hasSubscribedNewAppointmentMessage");
    
    const templates = [
      {
        id: "o7WljBjHOvNPXVvRdRO9pHFIOLO_pgbz3oc-WI4lng0",
        name: "取消预约通知",
        authorized: hasCancelMessage
      },
      {
        id: "ktex3oGhX7Bp8heWLu5dM10pRwXvtrQHEIkHNcNVGAQ",
        name: "新预约通知",
        authorized: hasNewAppointmentMessage
      }
    ];

    // 找出未授权的模板
    const missingTemplates = templates.filter(t => !t.authorized);
    
    if (missingTemplates.length === 0) {
      wx.showToast({
        title: "所有通知已授权",
        icon: "success",
      });
      return;
    }

    // 只请求第一个未授权的模板（用户需要多次点击来完成所有授权）
    const templateToRequest = missingTemplates[0];
    
    wx.requestSubscribeMessage({
      tmplIds: [templateToRequest.id],
      success: (res) => {
        console.log(`${templateToRequest.name} 授权结果:`, res);
        const status = res[templateToRequest.id];
        
        if (status === "accept") {
          // 保存授权状态
          if (templateToRequest.id === "o7WljBjHOvNPXVvRdRO9pHFIOLO_pgbz3oc-WI4lng0") {
            wx.setStorageSync("hasSubscribedCancelMessage", true);
          } else {
            wx.setStorageSync("hasSubscribedNewAppointmentMessage", true);
          }
          
          // 检查是否所有模板都已授权
          const allAuthorized = templates.every(t => 
            t.authorized || (t.id === templateToRequest.id && status === "accept")
          );
          
          if (allAuthorized) {
            wx.setStorageSync("hasSubscribedMessage", true);
            wx.showToast({
              title: "已开启所有消息通知",
              icon: "success",
            });
          } else {
            // 还有未授权的模板，提示用户继续授权
            const remainingTemplates = templates.filter(t => 
              !t.authorized && t.id !== templateToRequest.id
            );
            if (remainingTemplates.length > 0) {
              wx.showModal({
                title: "继续授权",
                content: `${templateToRequest.name}已授权✅\n\n还需要授权'${remainingTemplates[0].name}'，请再次点击授权按钮。`,
                showCancel: false,
                confirmText: "知道了",
              });
            }
          }
        } else {
          wx.showToast({
            title: "授权失败，请重试",
            icon: "none",
          });
        }
      },
      fail: (err) => {
        console.error(`${templateToRequest.name} 授权失败:`, err);
        wx.showToast({
          title: "授权失败，请重试",
          icon: "none",
        });
      },
    });
  },

  /**
   * 退出登录
   */
  logout() {
    wx.showModal({
      title: "确认退出",
      content: "确定要退出登录吗？",
      success: (res) => {
        if (res.confirm) {
          // 清除用户信息和token
          wx.removeStorageSync("userInfo");
          wx.removeStorageSync("token");

          // 清除其他相关数据
          wx.removeStorageSync("products");
          wx.removeStorageSync("bannerImages");
          wx.removeStorageSync("workTimes");

          wx.showToast({
            title: "已退出登录",
            icon: "success",
          });

          // 刷新当前页面数据
          this.checkAdminStatus();
          this.loadUserData();

          // 更新tabBar
          const app = getApp();
          if (app && app.updateTabBar) {
            app.updateTabBar();
          }
        }
      },
    });
  },

  /**
   * 跳转到登录页面
   */
  goToLogin() {
    wx.navigateTo({
      url: "/pages/login/index",
    });
  },

  /**
   * 跳转到隐私政策页面
   */
  goToPrivacy() {
    wx.navigateTo({
      url: "/pages/privacy/index",
    });
  },

  userManage() {
    wx.navigateTo({
      url: "/pages/userManage/index",
    });
  },

  /**
   * 注销账号
   */
  deleteAccount() {
    wx.showModal({
      title: "注销账号",
      content:
        "注销后将永久删除您的账号和所有相关数据，此操作不可恢复。确定要继续吗？",
      confirmText: "确认注销",
      cancelText: "取消",
      confirmColor: "#ff4757",
      success: async (res) => {
        if (res.confirm) {
          // 二次确认
          wx.showModal({
            title: "最后确认",
            content: "请再次确认：注销后您的所有数据将被永久删除，无法恢复！",
            confirmText: "确认删除",
            cancelText: "取消",
            confirmColor: "#ff4757",
            success: async (res2) => {
              if (res2.confirm) {
                try {
                  wx.showLoading({
                    title: "注销中...",
                  });

                  // 调用后端API删除用户数据
                  const { userApi } = require("../../utils/api.js");
                  const result = await userApi.deleteAccount();

                  wx.hideLoading();

                  if (result.code === 0) {
                    // 清除本地所有数据
                    wx.clearStorageSync();

                    wx.showToast({
                      title: "账号已注销",
                      icon: "success",
                    });

                    // 跳转到登录页面
                    setTimeout(() => {
                      wx.reLaunch({
                        url: "/pages/login/index",
                      });
                    }, 1500);
                  } else {
                    wx.showToast({
                      title: result.message || "注销失败",
                      icon: "none",
                    });
                  }
                } catch (error) {
                  wx.hideLoading();
                  wx.showToast({
                    title: "注销失败，请重试",
                    icon: "none",
                  });
                }
              }
            },
          });
        }
      },
    });
  },

  /**
   * 商品维护
   */
  productMaintain() {
    wx.navigateTo({
      url: "/pages/productMaintain/index",
    });
  },

  /**
   * 我的预约
   */
  myAppointments() {
    // 检查用户是否已登录
    const userInfo = wx.getStorageSync("userInfo");
    if (!userInfo) {
      wx.showModal({
        title: "需要登录",
        content: "请先登录后再查看预约记录",
        confirmText: "去登录",
        cancelText: "取消",
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: "/pages/login/index",
            });
          }
        },
      });
      return;
    }

    wx.navigateTo({
      url: "/pages/appointmentManage/index",
    });
  },

  /**
   * 联系客服
   */
  contactService() {
    wx.showActionSheet({
      itemList: ["拨打电话"],
      success: (res) => {
        if (res.tapIndex === 0) {
          wx.makePhoneCall({
            phoneNumber: "18249606870",
          });
        }
      },
    });
  },

  /**
   * 管理轮播图
   */
  manageBannerImages() {
    wx.showActionSheet({
      itemList: ["上传轮播图", "查看轮播图", "删除轮播图"],
      success: (res) => {
        switch (res.tapIndex) {
          case 0:
            this.uploadBannerImage();
            break;
          case 1:
            this.viewBannerImages();
            break;
          case 2:
            this.deleteBannerImage();
            break;
        }
      },
    });
  },

  /**
   * 上传轮播图
   */
  async uploadBannerImage() {
    wx.chooseImage({
      count: 9,
      sizeType: ["compressed"],
      sourceType: ["album", "camera"],
      success: async (res) => {
        const tempFilePaths = res.tempFilePaths;

        wx.showLoading({
          title: "上传中...",
        });

        try {
          let successCount = 0;
          let failCount = 0;

          // 逐个上传图片到服务器
          for (let i = 0; i < tempFilePaths.length; i++) {
            const path = tempFilePaths[i];

            try {
              // 上传图片到服务器
              const { productApi } = require("../../utils/api.js");
              const uploadResult = await productApi.uploadImage(path);

              if (uploadResult.code === 0) {
                // 创建轮播图记录
                const { bannerApi } = require("../../utils/api.js");
                const bannerResult = await bannerApi.createBanner({
                  title: `轮播图${i + 1}`,
                  image_url: uploadResult.data.url,
                  link_url: "/pages/appointment/appointment",
                  sort_order: 0,
                  status: 1,
                });

                if (bannerResult.code === 0) {
                  successCount++;
                } else {
                  failCount++;
                }
              } else {
                failCount++;
              }
            } catch (uploadError) {
              failCount++;
            }
          }

          wx.hideLoading();

          // 根据上传结果显示不同的提示
          if (successCount > 0 && failCount === 0) {
            wx.showToast({
              title: `成功上传${successCount}张轮播图`,
              icon: "success",
              duration: 2000,
            });
          } else if (successCount > 0 && failCount > 0) {
            wx.showToast({
              title: `成功上传${successCount}张，失败${failCount}张`,
              icon: "none",
              duration: 3000,
            });
          } else {
            wx.showToast({
              title: "上传失败，请重试",
              icon: "none",
              duration: 2000,
            });
          }

          // 通知首页更新轮播图
          this.notifyHomePageUpdate();
        } catch (error) {
          wx.hideLoading();
          wx.showToast({
            title: "上传失败，请重试",
            icon: "none",
            duration: 2000,
          });
        }
      },
      fail: () => {
        // 用户取消选择图片，不显示提示
      },
    });
  },

  /**
   * 查看轮播图
   */
  async viewBannerImages() {
    try {
      const { bannerApi } = require("../../utils/api.js");
      const result = await bannerApi.getBanners();

      if (result.code === 0 && result.data && result.data.length > 0) {
        const urls = result.data.map((img) => img.image_url);
        wx.previewImage({
          urls: urls,
          current: urls[0],
        });
      } else {
        wx.showToast({
          title: "暂无轮播图可查看",
          icon: "none",
          duration: 2000,
        });
      }
    } catch (error) {
      wx.showToast({
        title: "查看轮播图失败",
        icon: "none",
        duration: 2000,
      });
    }
  },

  /**
   * 删除轮播图
   */
  async deleteBannerImage() {
    try {
      const { bannerApi } = require("../../utils/api.js");
      const result = await bannerApi.getBanners();

      if (result.code === 0 && result.data && result.data.length > 0) {
        const items = result.data.map((img, index) => `轮播图${index + 1}`);
        items.push("全部删除");

        wx.showActionSheet({
          itemList: items,
          success: async (res) => {
            if (res.tapIndex === items.length - 1) {
              // 全部删除
              this.deleteAllBannerImages();
            } else {
              // 删除单个
              const bannerId = result.data[res.tapIndex].id;
              this.deleteSingleBannerImage(bannerId);
            }
          },
          fail: () => {
            // 用户取消选择，不显示提示
          },
        });
      } else {
        wx.showToast({
          title: "暂无轮播图可删除",
          icon: "none",
          duration: 2000,
        });
      }
    } catch (error) {
      wx.showToast({
        title: "获取轮播图失败",
        icon: "none",
        duration: 2000,
      });
    }
  },

  /**
   * 删除单个轮播图
   */
  async deleteSingleBannerImage(bannerId) {
    try {
      const { bannerApi } = require("../../utils/api.js");
      const result = await bannerApi.deleteBanner(bannerId);

      if (result.code === 0) {
        wx.showToast({
          title: "轮播图删除成功",
          icon: "success",
          duration: 2000,
        });

        // 通知首页更新轮播图
        this.notifyHomePageUpdate();
      } else {
        throw new Error(result.message || "删除失败");
      }
    } catch (error) {
      wx.showToast({
        title: "删除失败，请重试",
        icon: "none",
        duration: 2000,
      });
    }
  },

  /**
   * 删除所有轮播图
   */
  async deleteAllBannerImages() {
    wx.showModal({
      title: "确认删除",
      content: "确定要删除所有轮播图吗？",
      success: async (res) => {
        if (res.confirm) {
          try {
            const { bannerApi } = require("../../utils/api.js");
            const result = await bannerApi.getBanners();

            if (result.code === 0 && result.data) {
              // 逐个删除所有轮播图
              for (const banner of result.data) {
                await bannerApi.deleteBanner(banner.id);
              }
            }

            wx.showToast({
              title: "所有轮播图删除成功",
              icon: "success",
              duration: 2000,
            });

            // 通知首页更新轮播图
            this.notifyHomePageUpdate();
          } catch (error) {
            wx.showToast({
              title: "删除失败，请重试",
              icon: "none",
              duration: 2000,
            });
          }
        }
      },
    });
  },

  /**
   * 通知首页更新轮播图
   */
  notifyHomePageUpdate() {
    // 使用事件总线通知首页更新
    wx.eventBus = wx.eventBus || {};
    wx.eventBus.emit("bannerUpdated");

    // 也可以使用页面间通信
    const pages = getCurrentPages();
    const homePage = pages.find((page) => page.route === "pages/home/index");
    if (homePage && homePage.loadBannerData) {
      homePage.loadBannerData();
    }
  },

  /**
   * 跳转到完善信息页面
   */
  goToCompleteProfile() {
    // 检查用户是否已登录
    const userInfo = wx.getStorageSync("userInfo");
    if (!userInfo) {
      const { userSettings } = this.data;
      const title = userSettings.setting1 || "";

      wx.showModal({
        title: "需要登录",
        content: `请先登录后再${title}`,
        confirmText: "去登录",
        cancelText: "取消",
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: "/pages/login/index",
            });
          }
        },
      });
      return;
    }

    wx.navigateTo({
      url: "/pages/completeProfile/index",
    });
  },

  /**
   * 检查服务器状态
   */
  async checkServerStatus() {
    const { showServerStatus } = require("../../utils/serverStatus.js");
    await showServerStatus();
  },

  /**
   * 下拉刷新
   */
  async onPullDownRefresh() {
    try {
      // 并行加载所有数据
      await Promise.all([
        this.loadUserData(),
        this.loadStatistics(),
        this.loadUserSettings(),
      ]);
    } catch (error) {
      // 即使加载失败也要停止刷新动画
    } finally {
      // 确保停止下拉刷新动画
      wx.stopPullDownRefresh();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: "甲年华美甲美睫 - 个人中心",
      desc: "管理您的预约和账户信息，享受专属服务",
      path: "/pages/personalCenter/index",
      imageUrl: "/images/share-personal.jpg",
    };
  },

  /**
   * 分享到朋友圈
   */
  onShareTimeline() {
    return {
      title: "甲年华美甲美睫 - 个人中心",
      query: "",
      imageUrl: "/images/share-personal.jpg",
    };
  },
});
